<template>
    <view class="xilu">
        <view class="page-foot bg-white" @click="formSubmit()">
            <view class="btn1">立即发布</view>
        </view>
        <view class="container">
            <view class="topic" @click="openPop()">
                <view class="flex-box flex-between xilu_choose">
                    <view class="fs34 col3 fwb">选择话题</view>
                </view>
                <view class="flex-box pt30" v-if="topicIndex>=0">
                    <image :src="topicList[topicIndex].image_text" mode="aspectFill" class="xilu_topic_pic"></image>
                    <view>
                        <view class="fs30 col3 pb5">{{topicList[topicIndex].name}}</view>
                        <view class="fs24 cola">{{topicList[topicIndex].join_users}}人讨论</view>
                    </view>
                </view>
            </view>
            <textarea class="xilu_text fs30" maxlength="600" v-model="content" placeholder="请输入你要发布的内容～"
                placeholder-class="colc"></textarea>
            <view class="fs34 col10 plr30 pb30 fwb">图片</view>
            <view class="plr30">
                <u-upload :fileList="fileListimages" @afterRead="afterRead" @delete="deletePic" name="images" multiple="true"
                    :maxCount="9" width="210" height="210" :previewFullImage="true"></u-upload>
            </view>
        </view>
        <u-popup :show="show" @close="closePop">
            <view class="xilu_pop">
                <view class="fs30 col10 tc ptb30">选择话题</view>
                 <image src="../../static/icon/pop_close.png" class="xilu_pop_close" mode="aspectFill" @click="closePop"></image>
                <view class="xilu_topc_list">
                    <view class="flex-box pt30" v-for="(item,index) in topicList" @click="bindChoose(index)">
                        <image :src="item.image_text" mode="aspectFill" class="xilu_topic_pic"></image>
                        <view>
                            <view class="fs30 col3 pb5">{{item.name}}</view>
                            <view class="fs24 cola">{{item.join_users}}人讨论</view>
                        </view>
                    </view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import form from "../../uni_modules/uview-ui/libs/config/props/form.js";
	var validate = require("../../xilu/validate.js");
    export default {
        data() {
            return {
                fileListimages: [],
				topicList:[],
				topicMore:{page:1},
				topicIndex: -1,
                show: false,
				content:'',
            };	
        },
		onLoad(options) {
			this.fetchTopic()
		},
        methods: {
			//获取话题
			fetchTopic(){
				let query = {};
				query.pagesize = 20;
				this.$util.fetch(this, 'xilumarket.topic/lists', query, 'topicMore', 'topicList', 'data', data=>{
				
				})
			},
            closePop() {
                this.show = false;
            },
            openPop() {
                this.show = true;
            },
			//选择话题
			bindChoose(index){
				this.topicIndex = index;
				this.closePop();
			},
            // 删除图片
            deletePic(event) {
                this[`fileList${event.name}`].splice(event.index, 1)
            },
            // 新增图片
            async afterRead(event) {
                // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
                let lists = [].concat(event.file)
                let fileListLen = this[`fileList${event.name}`].length
                lists.map((item) => {
                    this[`fileList${event.name}`].push({
                        ...item,
                        status: 'uploading',
                        message: '上传中'
                    })
                })
                for (let i = 0; i < lists.length; i++) {
                    const result = await this.uploadFilePromise(lists[i].url)
                    let item = this[`fileList${event.name}`][fileListLen]
                    this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    }))
                    fileListLen++
                }
            },
            uploadFilePromise(filepath) {
				let page = this;
                return new Promise((resolve, reject) => {
					page.$core.uploadFile({
						filePath: filepath,
						success: (ret, response) => {
							 resolve(ret.data.url)
						}
					})
                })
            },
			
			formSubmit() {
			    let formData = {
					topic_id: this.topicIndex>=0?this.topicList[this.topicIndex].id:0,
					content: this.content.trim(),
				}
				let images = []
				this.fileListimages.forEach(item=>images.push(item.url));
				formData.images = images.join(',');
			    var rule = [
					// {
			  //           name: 'topic_id',
			  //           nameChn: '话题',
			  //           rules: ['require','gt:0'],
			  //           errorMsg: {
					// 		require: '请选择话题',
			  //               gt: '请选择话题'
			  //           },
			  //       },
					{
					    name: 'content',
					    nameChn: '内容',
					    rules: ['require','length:1,600'],
					    errorMsg: {
					        require: '请填写帖子内容',
							length: "帖子限制600字"
					    },
					},
					];
			    // 是否全部通过，返回Boolean
				//console.log(validate.check(formData,rule),validate.getError(),formData);
			
				if(!validate.check(formData,rule)){
					uni.showToast({
						title: validate.getError()[0],
						icon:'none'
					});
					return ;
				}
				this.$core.post({url:'xilumarket.forum/add_forum',data:formData,success:ret=>{
					uni.showModal({
						title: '提示',
						content:'发布成功，等待审核',
						showCancel:false,
						success(res) {
							uni.navigateBack({});
						}
					});
				}})
			}
        }
    }
</script>

<style lang="scss" scoped>
    .xilu {
        .topic {
            width: 690rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            margin: 30rpx auto;
            padding: 35rpx 30rpx 30rpx;
        }

        &_choose::after {
            content: "";
            display: block;
            width: 35rpx;
            height: 35rpx;
            background: url(../../static/icon/placeorder_right2.png) no-repeat center;
            background-size: 100%;
        }

        &_topic_pic {
            width: 65rpx;
            height: 65rpx;
            margin-right: 20rpx;
            border-radius: 15rpx;
        }

        &_text {
            width: 690rpx;
            height: 500rpx;
            background: #F7F9FC;
            border-radius: 20rpx;
            margin: 40rpx auto;
            padding: 30rpx;
        }


        &_topc_list {
            height: 50vh;
            overflow-y: scroll;
            padding: 0 30rpx;
            position: relative;

            @supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
                .flex-box:last-child {
                    padding-bottom: calc(68rpx);
                    padding-bottom: calc(constant(safe-area-inset-bottom));
                    padding-bottom: calc(env(safe-area-inset-bottom));
                }
            }
        }
        &_pop{
            position: relative;
        }

        &_pop_close {
            width: 35rpx;
            height: 35rpx;
            position: absolute;
            top: 32rpx;
            right: 30rpx;
        }
    }
</style>
